package com.mycode.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.DefaultEventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * 两组 EventLoop 并使用独立的 EventLoop 实现操作
 */
@Slf4j
public class TwoGroupEventLoopServer2 {

    public static void main(String[] args) {
        // boss group 只负责连接
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        // worker group 只负责读写
        NioEventLoopGroup workers = new NioEventLoopGroup(2);
        DefaultEventLoopGroup nonIOWorkers = new DefaultEventLoopGroup(2);
        new ServerBootstrap()
                .group(boss, workers)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        // 普通的 Handler 处理器
                        ch.pipeline().addLast(nonIOWorkers, "nonIOWorkers", new ChannelInboundHandlerAdapter() {
                            // Object msg 现在没有解码 是 ByteBuf 类型
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.debug(buf.toString(CharsetUtil.UTF_8));
                                // 将消息传入到 下一个 handler
                                ctx.fireChannelRead(msg);
                            }
                        });
                        ch.pipeline().addLast("IOWorkers", new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.debug(buf.toString(CharsetUtil.UTF_8));
                            }
                        });
                    }
                })
                .bind(8080);
    }

}
